package com.neuedu.javase.io;

import java.io.*;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-05 13:36
 * 描述 : 对象的读写
 */
public class MyObjectStream {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //将内存对象输出到文件中
//        writeObject();

        //从文件中读取对象
        readObject();
    }


    //获取对象， 反序列化
    public static void readObject() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\io\\course1.obj"));
        //要求对象支持
        Course course = (Course) ois.readObject(); //ClassNotFoundException
        System.out.println(course);
        ois.close();
    }


    /**
     * 持久化到文件中（序列化）
     * @throws IOException
     */
    public static void writeObject() throws IOException {
        Course course = new Course();
        course.setCourseName("计算机网络");
        course.setPassword("123456");

        System.out.println("course = " + course);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\io\\course1.obj"));
        //要求对象支持
        oos.writeObject(course);
        oos.close();
    }


}
